<template>
  <div id="map" :style="mapLayout"></div>
</template>

<script>
import { loadModules } from 'esri-loader'
import { mapState } from 'vuex'

export default {
  name: 'ArcGisSwitchMap',
  data () {
    return {
      view: null,
      // 默认底图
      defaultBaseMap: 'osm'
    }
  },
  computed: {
    ...mapState({
      mapLayout: state => {
        return {
          width: '100%',
          height: state.layoutHeight - 48 + 'px'
        }
      }
    })
  },
  mounted () {
    loadModules(['esri/Map', 'esri/views/MapView'], { css: true })
      .then(([ArcGISMap, MapView]) => {
        // 配置地图的底图
        const map = new ArcGISMap({
          basemap: this.defaultBaseMap
        })
        // 地图视图对象
        this.view = new MapView({
          // 容器
          container: document.getElementById('map'),
          // 中心点
          center: [117.129359, 31.839979],
          map: map,
          // 缩放
          zoom: 14
        })

        // 将自定义的tool添加到视图中
        // https://developers.arcgis.com/javascript/latest/api-reference/esri-views-ui-DefaultUI.html#add
        this.view.ui.add(this.switchMapBtn(map), 'top-left')
      })
  },
  methods: {
    // 地图切换按钮
    switchMapBtn (map) {
      const btn = document.createElement('img')
      btn.src = require('@/assets/img/switch-map.jpg')
      btn.style.width = '32px'
      btn.style.height = '32px'
      btn.style.cursor = 'pointer'
      btn.onclick = () => {
        // https://developers.arcgis.com/javascript/latest/api-reference/esri-Map.html#basemap
        this.defaultBaseMap = map.basemap = this.defaultBaseMap === 'osm' ? 'satellite' : 'osm'
      }
      return btn
    }
  },
  beforeDestroy () {
    this.view = null
  }
}
</script>

<style scoped>
</style>
